package com.maybach.web.controller.certificate;

import com.maybach.common.po.ProviderCertificatePO;
import com.maybach.core.ao.CertificateAO;
import com.maybach.core.ao.FlowApplyAO;
import com.maybach.core.ao.UserAO;
import com.maybach.core.form.certificate.ProviderAuditForm;
import com.maybach.core.form.partner.PartnerQueryForm;
import com.maybach.util.query.support.PageResult;
import com.maybach.web.constants.WebConstants;
import com.maybach.web.framework.util.WebUtil;
import com.maybach.workflow.common.api.enums.FlowActTypeEnum;
import com.maybach.workflow.common.api.enums.FlowStateEnum;
import com.maybach.workflow.common.model.FlowApplyDO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;

/**
 * Created by houenxun on 16/1/22.
 * 供应商信息认证
 */
@Controller
@RequestMapping("/certificate/provider/")
public class ProviderCertificateController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserAO userAO;

    @Autowired
    private FlowApplyAO flowApplyAO;

    @Autowired
    private CertificateAO certificateAO;


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }


    /**
     * 用户认证管理页面
     *
     * @return
     */
    @RequiresAuthentication
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list(@ModelAttribute("partnerQueryForm") PartnerQueryForm partnerQueryForm, BindingResult bindingResult, ModelMap model) {
        if (null == partnerQueryForm) {
            partnerQueryForm = new PartnerQueryForm();
        }
        if (!model.containsAttribute("partnerQueryForm")) {
            model.addAttribute(partnerQueryForm);
        }
        try {
            if (null == partnerQueryForm.getStatus()) {
                partnerQueryForm.setStatus(Arrays.asList(FlowStateEnum.init.getStatus(), FlowStateEnum.reject.getStatus()));
            }
            PageResult<FlowApplyDO> result = certificateAO.queryProviderCertificate(partnerQueryForm);
            model.addAttribute("pageResult", result);
            return "certificate/provider/list";

        } catch (Exception e) {
            logger.error("", e);
            return "result";
        }
    }

    @RequiresAuthentication
    @RequestMapping(value = "audit")
    public String audit(@RequestParam("taskId") Long taskId, @RequestParam(required = false, value = "redirectUrl") String redirectUrl, Model model) {

        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);

        FlowApplyDO applyDO = flowApplyAO.getApplyByTaskId(taskId);
        model.addAttribute("applyDO", applyDO);
        ProviderCertificatePO certificatePO = (ProviderCertificatePO) applyDO.getContentObject();




        if (!model.containsAttribute("taskActForm")) {
            ProviderAuditForm taskActForm = new ProviderAuditForm();
            taskActForm.setTaskId(taskId);
            taskActForm.setContractImgs(certificatePO.getContractImgs());
            model.addAttribute("taskActForm", taskActForm);
        }


        return "certificate/provider/audit";
    }


    @RequestMapping(value = "doAudit", method = RequestMethod.POST)
    @RequiresAuthentication
    public String doAudit(HttpServletRequest request, @RequestParam(required = false, value = "redirectUrl") String redirectUrl, @Valid @ModelAttribute("taskActForm") ProviderAuditForm taskActForm, BindingResult bindingResult,  ModelMap model, RedirectAttributes redirectAttributes) throws Exception {
        model.addAttribute(WebConstants.REDIRECT_URL_KEY, redirectUrl);
        if(StringUtils.isNotBlank(taskActForm.getActType())&& taskActForm.getActType().equals(FlowActTypeEnum.pass.getCode())){
            if(CollectionUtils.isEmpty(taskActForm.getContractImgs())){
                bindingResult.addError(new FieldError("taskActForm", "contractImgs", "请上传协议资料"));
            }
        }
        if (bindingResult.hasErrors()) {
            WebUtil.storeFlashAttribute(redirectAttributes, model);
            return "redirect:" + WebUtil.getLastUrlFromReferer(request);
        }

        FlowApplyDO flowApplyDO = flowApplyAO.getApplyByTaskId(taskActForm.getTaskId());
        ProviderCertificatePO certificatePO = (ProviderCertificatePO) flowApplyDO.getContentObject();
        certificatePO.setContractImgs(taskActForm.getContractImgs());
        flowApplyDO.setContentObject(certificatePO);
        flowApplyAO.updateApply(flowApplyDO);

        flowApplyAO.executeTask(taskActForm);
        return WebConstants.COMMON_RESULT_PAGE;
    }


}
